<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/12/4
 * Time: 14:55
 */

namespace common\business\empdept;


use common\business\task\TaskHandler;
use common\business\task\TaskHelper;
use common\business\task\TaskResponseData;
use common\consts\CommonResources;
use common\models\Task;
use yii\helpers\Json;

class EmployeeDepartmentTaskHandler extends TaskHandler
{
    /**
     * @param Task|null|array $task
     * @return TaskResponseData
     */
    public function process($task)
    {
        $department_number = '';
        $requestDataArr = Json::decode($task->request_data, true);
        if (sizeof($requestDataArr) > 0){
            foreach ($requestDataArr as $reqKey => $reqValue){
                if (strtolower($reqKey) == strtolower('department_number')) {
                    $department_number = $reqValue;
                }
            }
        }

        $writeBackHandler = function ($totalCount, $finishCount, $message) use ($task){
            TaskHelper::writeBackAlways($task, $totalCount, $finishCount, $message);
        };

        $service = new EmployeeDepartmentService();
        $result = $service->sync($writeBackHandler, $department_number);

        TaskHelper::finishTask($task, $result->total_count, $result->total_count, $result->getMessage());
        if (!$result->isSuccess){
            return new TaskResponseData(TaskResponseData::CODE_ERROR, CommonResources::ACTION_FAIL_MSG('Sync', 'EmployeeDepartment', $result->message));
        }
        return new TaskResponseData(TaskResponseData::CODE_SUCCESS, CommonResources::ACTION_SUCCESS_MSG_DETAIL('Sync', 'EmployeeDepartment', $result->message));
    }
}